package game.targets;

import game.targets.entity.CollisionEntity;

import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.physics.bullet.collision.LocalRayResult;
import com.badlogic.gdx.physics.bullet.collision.RayResultCallback;
import com.badlogic.gdx.physics.bullet.collision.btCollisionObject;
import com.badlogic.gdx.physics.bullet.linearmath.btVector3;

public class RayCallback extends RayResultCallback {
	Vector3 m_rayFromWorld;
	Vector3 m_rayToWorld;
	btVector3 m_hitNormalWorld;
	Vector3 hitPointWorld;
	float m_closestHitFraction;
	btCollisionObject object;
	CollisionEntity entityHit;
	boolean hit;

	public RayCallback() {
		super();
		object = new btCollisionObject();
		m_rayFromWorld = new Vector3();
		m_rayToWorld = new Vector3();
		hitPointWorld = new Vector3();
		m_hitNormalWorld = new btVector3();
		m_closestHitFraction = 1000000;
		entityHit = null;
		hit = false;
	}

	@Override
	public float addSingleResult(LocalRayResult rayResult, boolean normalInWorldSpace) {
		entityHit=null;
		hit = true;
		if (rayResult.getHitFraction() < m_closestHitFraction)
			m_closestHitFraction = rayResult.getHitFraction();

		object = rayResult.getCollisionObject();
		entityHit=(CollisionEntity) object.userData;
		if (normalInWorldSpace) {
			m_hitNormalWorld = rayResult.getHitNormalLocal();
		} else {
			// m_hitNormalWorld =
			// m_collisionObject->getWorldTransform().getBasis() *
			// rayResult.getHitNormalLocal();
		}

		hitPointWorld= m_rayFromWorld.lerp(m_rayToWorld, m_closestHitFraction);
		return 1.0f;
	}

	@Override
	public boolean hasHit() {
		return hit;

	}

	public void clear() {
		hit = false;
		m_closestHitFraction=1000000;
	}

	/*
	 * @Override public float addSingleResult (btManifoldPoint cp,
	 * btCollisionObjectWrapper colObj0Wrap, int partId0, int index0,
	 * btCollisionObjectWrapper colObj1Wrap, int partId1, int index1) { other =
	 * colObj0Wrap.getCollisionObject() == movingBox.body ?
	 * colObj1Wrap.getCollisionObject() : colObj0Wrap.getCollisionObject();
	 * 
	 * return 0f; }
	 */

	public CollisionEntity getEntityHit() {
		return entityHit;
	}

	public void setEntityHit(CollisionEntity entityHit) {
		this.entityHit = entityHit;
	}

	public Vector3 gethitPointWorld() {
		return hitPointWorld;
	}

	public void sethitPointWorld(Vector3 m_hitPointWorld) {
		this.hitPointWorld = m_hitPointWorld;
	}

	public void setPositions(Vector3 position, Vector3 selection) {
		m_rayFromWorld = position.cpy();
		m_rayToWorld = selection.cpy();

	}

}
